package it.cst.entity.controller;



import it.cst.entity.User;
import it.cst.entity.service.RoleService;
import it.cst.entity.service.UserService;
import it.cst.util.Roles;

import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	@RequestMapping("/login")
	public String login() {
		return "login";
	}
	
	@RequestMapping("/logout")
	public String logout() {
		return "logout";
	}



	@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
	public String saveUser(@RequestParam(value="username") String userName, @RequestParam(value="firstname") String firstName, @RequestParam(value="lastname") String lastName, @RequestParam(value="email") String email, @RequestParam(value="role") String role, @RequestParam(value="notify") String notify) {
		User user = userService.getUser(userName);
		user.setFirstname(firstName);
		user.setLastname(lastName);
		user.setEmail(email);
		user.setNotify(Boolean.parseBoolean(notify));
		Roles roles = Roles.getInstance(roleService);
		user.setDefaultrole(roles.getRole(role).getId());
		for(User u : userService.listUser()){
			if(!u.getUsername().equalsIgnoreCase(userName)){
				if((u.getFirstname().equalsIgnoreCase(firstName) && u.getLastname().equalsIgnoreCase(lastName)) || u.getEmail().equalsIgnoreCase(email)){
					return "userProfileError";
				}
			}
		}
		userService.saveUser(user);
		return "userProfile";
	}

	
	
	@RequestMapping(value = "/setNewPwd", method = RequestMethod.POST)
	public String setNewPwd(@RequestParam(value="username") String userName, @RequestParam(value="oldPwd") String oldPwd, @RequestParam(value="newPwd") String newPwd, @RequestParam(value="confNewPwd") String confNewPwd) {
		User user = userService.getUser(userName);
		user.setPassword(newPwd);
		userService.saveUser(user);
		return "userProfile";
	}

	@RequestMapping("/changePwd")
	public String changePwd() {
		return "changePwd";
	}
	
	
	@RequestMapping("/deleteuser/{userId}")
	public String deleteContact(@PathVariable("userId")
	Integer userId) {
		userService.removeUser(userId);
		return "redirect:/index";
	}
	
	@RequestMapping("/userProfile")
	public String userProfile() {
		return "userProfile";
	}

	
	@RequestMapping("/home")
	public String landing(Map<String, Object> map) {
//		map.put("user", new User());
//		map.put("userList", userService.listUser());
		return "home";
	}
}
